{% extends "./base.html" %}
{% load admin_utils %}

{% block main_content %}
<div id="app-memberships-wrapper">
    <h3>实例详情</h3>
    <div v-if="unbound_service_instance_list.length > 0">
        应用有 $[ unbound_service_instance_list.length ] 个已解绑但未回收的增强服务实例。 <a href="javascript:void(0)" @click="showRecycleInstanceDialog">立即回收</a>
    </div>
    <bk-table style="margin-top: 15px;"
        :data="service_instance_list"
        :cell-class-name="cellStyleCallback">
        <bk-table-column label="服务logo" prop="module" width="100px">
            <template slot-scope="props">
                <img class="service-logo" :src="props.row.service.logo"/>
            </template>
        </bk-table-column>
        <bk-table-column label="服务名称" prop="service.display_name"></bk-table-column>
        <bk-table-column label="绑定模块" prop="module">
            <template slot-scope="props">
                <span>$[ props.row.module  ]</span>
            </template>
        </bk-table-column>
        <bk-table-column label="使用环境" prop="environment.environment"></bk-table-column>
        <bk-table-column label="配置信息">
            <template slot-scope="props">
                <json-pretty :data="props.row.instance" show-length highlight-mouseover-node :deep="0"></json-pretty>
            </template>
        </bk-table-column>
        <bk-table-column label="操作" width="150">
            <template slot-scope="props">
                <bk-button theme="primary" text @click="handleProvision(props.row)" v-if="props.row.instance === null">分配实例</bk-button>
                <bk-button theme="primary" text @click="handleDelete(props.row)" style="color: rgb(234, 54, 54);" v-else>删除实例</bk-button>
            </template>
        </bk-table-column>
    </bk-table>

    <bk-dialog v-model="recycleInstanceDialogVisible" header-position="left" width="1500px">
        <div slot="header">
            未回收的增强服务实例
        </div>
        <bk-table
            :data="unbound_service_instance_list"
            :cell-class-name="cellStyleCallback">
            <bk-table-column label="服务名称" prop="service.display_name"></bk-table-column>
            <bk-table-column label="绑定模块" prop="module">
                <template slot-scope="props">
                    <span>$[ props.row.module  ]</span>
                </template>
            </bk-table-column>
            <bk-table-column label="使用环境" prop="environment"></bk-table-column>
            <bk-table-column label="配置信息">
                <template slot-scope="props">
                    <json-pretty :data="props.row.instance" show-length highlight-mouseover-node :deep="0"></json-pretty>
                </template>
            </bk-table-column>
            <bk-table-column label="操作" width="150">
                <template slot-scope="props">
                    <bk-button theme="primary" text @click="handleRecycle(props.row)" style="color: rgb(234, 54, 54);">回收实例</bk-button>
                </template>
            </bk-table-column>
    </bk-dialog>
</div>
{% endblock %}

{% block main_script %}
<script>
    const application = {{ application | to_json }}

    const URLRouter = {
        list: decodeURI("{% url 'admin.applications.services.list' application.code %}"),
        delete: decodeURI("{% url 'admin.applications.services.recycle_resource' application.code '${module}' '${service_id}' '${instance_id}' %}"),
        provision: decodeURI("{% url 'admin.applications.services.provision' application.code '${module}' '${env}' '${service_id}' %}"),
        list_unbound: decodeURI("{% url 'admin.applications.services.unbound.list' application.code %}"),
        recycle: decodeURI("{% url 'admin.applications.services.unbound.recycle_resource' application.code '${module}' '${service_id}' '${instance_id}' %}"),
    }

    document.addEventListener('DOMContentLoaded', () => {
        new Vue({
            el: "#app-memberships-wrapper",
            delimiters: ['$[', ']'],
            data: function () {
                return {
                    application,
                    loading: false,
                    service_instance_list: [],
                    unbound_service_instance_list: [],
                    recycleInstanceDialogVisible: false,
                }
            },
            mounted: function () {
                console.log("mounted", this)
                this.fetchData()
            },
            methods: {
                fetchData () {
                    if (this.loading) {
                        return;
                    }
    
                    this.loading = true;
    
                    Promise.all([
                        this.$http.get(URLRouter.list),
                        this.$http.get(URLRouter.list_unbound)
                    ])
                    .then(([listResp, listUnboundResp]) => { 
                        this.service_instance_list = listResp || [];
                        this.unbound_service_instance_list = listUnboundResp || [];
                    })
                    .catch(err => {
                        console.error("Error fetching data:", err);
                    })
                    .finally(() => {
                        this.loading = false;
                    });
                },
                handleProvision: function (row) {
                    let url = URLRouter.provision.replace("${module}", row.module).replace("${env}", row.environment.environment).replace("${service_id}", row.service.uuid)
                    const h = this.$createElement
                    this.$bkInfo({
                        width: 500,
                        title: '确定要分配实例吗？',
                        subHeader: h('div', {
                            style: {
                                'color': 'red',
                                'text-align': 'center'
                            }
                        }, `即将为 ${row.module} 模块 ${row.environment.environment} 环境分配 ${row.service.name} 服务实例？`),
                        confirmLoading: true,
                        confirmFn: async () => {
                            try {
                                await this.$http.post(url)
                                this.$bkMessage({theme: 'success', message: '分配增强服务实例成功.'})
                                return true
                            } catch (e) {
                                this.$bkMessage({theme: 'error', message: '分配增强服务实例失败.'})
                                return false
                            } finally {
                                await this.fetchData()
                            }
                        }
                    })
                },
                handleDelete: function (row) {
                    let url = URLRouter.delete.replace("${module}", row.module).replace("${service_id}", row.service.uuid).replace("${instance_id}", row.instance.uuid)
                    const h = this.$createElement
                    this.$bkInfo({
                        width: 500,
                        title: '确认要删除吗？',
                        subHeader: h('div', {
                            style: {
                                'color': 'red',
                                'text-align': 'center'
                            }
                        }, `即将删除 ${row.module} 模块 ${row.environment.environment} 环境 ${row.service.name} 服务实例？`),
                        confirmLoading: true,
                        confirmFn: async () => {
                            try {

                                await this.$http.delete(url)
                                this.$bkMessage({theme: 'success', message: '删除增强服务实例成功.'})
                                return true
                            } catch (e) {
                                this.$bkMessage({theme: 'error', message: '删除增强服务实例失败.'})
                                return false
                            } finally {
                                await this.fetchData()
                            }
                        }
                    })
                },
                cellStyleCallback: function ({row, column, rowIndex, columnIndex}) {
                    if (column.label === "配置信息")
                        return 'json-view'
                },
                showRecycleInstanceDialog() {
                    this.recycleInstanceDialogVisible = true;
                },
                handleRecycle: function (row) {
                    let url = URLRouter.recycle.replace("${module}", row.module).replace("${service_id}", row.service.uuid).replace("${instance_id}", row.instance.uuid)
                    const h = this.$createElement
                    this.$bkInfo({
                        width: 500,
                        title: '确认要回收吗？',
                        subHeader: h('div', {
                            style: {
                                'color': 'red',
                                'text-align': 'center'
                            }
                        }, `即将回收 ${row.module} 模块 ${row.environment} 环境 ${row.service.name} 服务实例？`),
                        confirmLoading: true,
                        confirmFn: async () => {
                            try {
                                await this.$http.delete(url)
                                this.$bkMessage({theme: 'success', message: '回收增强服务实例成功.'})
                                return true
                            } catch (e) {
                                this.$bkMessage({theme: 'error', message: '回收增强服务实例失败.'})
                                return false
                            } finally {
                                await this.fetchData()
                            }
                        }
                    })
                },
            }
        })
    })
</script>
<style scoped>
    .service-logo{
        width: 35px;
        height: 35px;
        border-radius: 4px;
    }
</style>
{% endblock %}
